/*
 * @Author: shengduiliang 1107722390@qq.com
 * @Date: 2024-05-04 16:32:17
 * @LastEditors: shengduiliang 1107722390@qq.com
 * @LastEditTime: 2024-05-05 16:36:18
 * @FilePath: /treasure/src/ui-components/avatar-input/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Button, View } from "@tarojs/components"
import Taro from "@tarojs/taro"
import { uploadFile } from "@/network/upload"
import to from "await-to-js"
import { useCallback } from "react"
import { Avatar } from ".."
import './index.scss'

interface AvatarInputProps {
  avatar?: string
  placeholder: string
  onChange: (avatar: string) => void
}

const AvatarInput = ({ avatar, placeholder, onChange } : AvatarInputProps) => {

  const chooseAvatar = useCallback(async (avatarUrl: string) => {
    const [err, avatar] = await to(uploadFile(avatarUrl))
    if (err) return Taro.showToast({ title: '上传图片失败', icon: 'none' })
    onChange(avatar)
  }, [onChange])
  
  return (
    <View
      className='avatar-input pv-normal-mh-normal column-start-center'
    >
      <Button
        onChooseAvatar={(e) => chooseAvatar(e.detail.avatarUrl)} 
        openType='chooseAvatar'
        className='avatar-button'
      >
        { avatar && <Avatar avatar={avatar} />}
      </Button>
      <View className='text-primary mt-medium'>{placeholder}</View>
    </View>
  )
}

export default AvatarInput;

